package com.cgwx.service.impl;

import com.cgwx.config.BusinessException;
import com.cgwx.data.dto.UserRoomDto;
import com.cgwx.entity.*;
import com.cgwx.mapper.*;
import com.cgwx.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserRoomServiceImpl implements IUserRoomService {
    @Resource
    private IUserService userService;

    @Resource
    private IAuthorityService authorityService;

    @Resource
    private IFolderService folderService;

    @Resource
    private IRoomService roomService;

    @Resource
    private UserRoomMapper userRoomMapper;

    @Resource
    private FolderMapper folderMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private PersonalRecycleBinMapper personalRecycleBinMapper;

    @Resource
    private AuthorityMapper authorityMapper;

    @Override
    @Transactional
    public String insertUserRoom(String account, String entityId, String entityRoom, Timestamp time) {
        //权限
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userService.getUser(user).get(0);
        Authority authority = new Authority();
        authority.setPermissionType("staff");
        authority.setFileOrFolder("folder");
        authority.setEntityId(entityId);//根据情况改
        authority.setEntityName(getEntityNameByEntityId(entityId));
        authority.setPermissionId(account);
        authority.setPermissionName(user.getName());
        authority.setAuthorityLevel("2");
        authority.setId(authorityService.generateId());
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        boolean result = authorityService.insertAuthority(authority);
        if(!result) throw new BusinessException("权限表新增失败!");
        //用户空间表
        UserRoom userRoom = new UserRoom();
        userRoom.setAccount(account);
        userRoom.setEntityRoom(entityRoom);
        userRoom.setName(user.getName());
        if(!userRoomMapper.getUserRoom(userRoom).isEmpty()) throw new BusinessException(user.getName() + "已在该空间中!");
        userRoom.setDeptId(user.getDeptId());
        userRoom.setCreateTime(time);
        userRoom.setId(generateId());
        result = userRoomMapper.insertUserRoom(userRoom);
        if(!result) throw new BusinessException("员工空间表新增失败!");
        return "员工空间表新增成功!";
    }

    @Transactional
    @Override
    public String freeRoomInsertStaff(String account, String deptId, String entityId, List<String> accountList) {
        //鉴权
        int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
        if(level < 3) throw new BusinessException("您没有管理权限!");
        //权限
        List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
        Folder folder = new Folder();
        folder.setEntityId(entityId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        UsUser user;
        Authority authority = new Authority();
        UserRoom userRoom = new UserRoom();
        authority.setPermissionType("staff");
        authority.setFileOrFolder("folder");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        userRoom.setEntityRoom(roomId);
        Room room = new Room();
        room.setId(roomId);
        room = roomService.getRoom(room).get(0);
        authority.setAuthorityLevel(room.getFreeAuth());
        for(String staffAccount: accountList) {
            userRoom.setDeptId(null);
            userRoom.setId(null);
            userRoom.setCreateTime(null);
            user = new UsUser();
            user.setAccount(staffAccount);
            user = userService.getUser(user).get(0);
            authority.setPermissionId(staffAccount);
            authority.setPermissionName(user.getName());
            for(String fileFolder: fileFolders){
                authority.setEntityId(fileFolder);//根据情况改
                authority.setEntityName(getEntityNameByEntityId(fileFolder));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result) {
                    log.error("freeRoomInsertStaff: 权限表新增失败!");
                    throw new BusinessException("权限表新增失败!");
                }
            }
            //用户空间表
            userRoom.setAccount(staffAccount);
            userRoom.setName(user.getName());
            if(!userRoomMapper.getUserRoom(userRoom).isEmpty()) throw new BusinessException(user.getName() + "已在该空间中!");
            userRoom.setDeptId(user.getDeptId());
            userRoom.setId(generateId());
            userRoom.setCreateTime(time);
            boolean result = userRoomMapper.insertUserRoom(userRoom);
            if(!result){
                log.error("freeRoomInsertStaff: 员工空间表新增失败!");
                throw new BusinessException("员工空间表新增失败!");
            }
        }
        return "员工空间表新增成功!";
    }

    @Transactional
    @Override
    public String freeRoomDeleteStaff(String account, String deptId, String entityId, List<String> accountList) {
        //鉴权
        int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
        if(level < 3) throw new BusinessException("您没有管理权限!");
        //权限
        List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
        Folder folder = new Folder();
        folder.setEntityId(entityId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        Authority authority = new Authority();
        UserRoom userRoom = new UserRoom();
        authority.setPermissionType("staff");
        userRoom.setEntityRoom(roomId);
        for(String staffAccount: accountList) {
            authority.setPermissionId(staffAccount);
            for(String fileFolder: fileFolders){
                authority.setEntityId(fileFolder);//根据情况改
                authorityMapper.deleteAuthority(authority);
            }
            //用户空间表
            userRoom.setAccount(staffAccount);
            boolean result = userRoomMapper.deleteUserRoom(userRoom);
            if(!result){
                log.error("freeRoomDeleteStaff: 用户空间表删除失败!");
                throw new BusinessException("用户空间表删除失败!");
            }
        }
        return "员工空间表删除成功!";
    }

    @Override
    public List<UserRoomDto> getUserRoomById(String entityRoom) {
        UserRoom userRoom = new UserRoom();
        userRoom.setEntityRoom(entityRoom);
        return userRoomMapper.getUserRoom(userRoom);
    }

    @Override
    public List<Room> getMyManageFreeRoomInfo(String account, String keyword, String column, String sort) {
        Room room = new Room();
        room.setRoomId(account);
        room.setRoomType("free");
        room.setRoomName(keyword);
        room.setColumn(column);
        room.setSort(sort);
        List<Room> rooms = roomService.getRoom(room);
        //AND room_name ~* #{roomName}
        for(Room room1 : rooms){
            List<UserRoom> userRooms = userRoomMapper.getUsersByEntityRoom(room1.getId());
            for(UserRoom userRoom1 : userRooms){
                room1.setUsers(room1.getUsers() + "," + userRoom1.getName());
            }
            if(room1.getUsers().startsWith("null,")) room1.setUsers(room1.getUsers().substring(5));
        }
        return rooms;
    }

    @Override
    public List<UserRoomDto> getMyFreeRoomInfo(String account, String keyword, String column, String sort) {
        UserRoom userRoom = new UserRoom();
        userRoom.setAccount(account);
        userRoom.setName(keyword);
        userRoom.setColumn(column);
        userRoom.setSort(sort);
        List<UserRoomDto> UserRoomDtos = userRoomMapper.getUserRoom(userRoom);
        for(UserRoomDto userRoomDto : UserRoomDtos){
            List<UserRoom> userRooms = userRoomMapper.getUsersByEntityRoom(userRoomDto.getEntityRoom());
            for(UserRoom userRoom1 : userRooms){
                userRoomDto.setUsers(userRoomDto.getUsers() + "," + userRoom1.getName());
            }
            if(userRoomDto.getUsers().startsWith("null,")) userRoomDto.setUsers(userRoomDto.getUsers().substring(5));
        }
        return UserRoomDtos;
    }

    @Override
    public boolean deleteUserRoomById(String entityRoom) {
        return userRoomMapper.deleteUserRoomById(entityRoom);
    }

    public String generateId() {
        return UUID.randomUUID().toString();
    }

    public String getEntityNameByEntityId(String entityId){
        if(entityId == null || entityId.isEmpty()) return null;
        else{
            if(entityId.startsWith("folder")){
                Folder folder = new Folder();
                folder.setEntityId(entityId);
                List<Folder> folders = folderMapper.getFolder(folder);
                if(folders == null || folders.isEmpty()){
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if(personalRecycleBins != null && personalRecycleBins.size() == 1) return personalRecycleBins.get(0).getEntityName();
                }
                else{
                    folder = folders.get(0);
                    return folder.getEntityName();
                }
            }
            else if(entityId.startsWith("file")){
                File file = new File();
                file.setEntityId(entityId);
                List<File> files = fileMapper.getFile(file);
                if(files == null || files.isEmpty()){
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if(personalRecycleBins != null && personalRecycleBins.size() == 1) return personalRecycleBins.get(0).getEntityName();
                }
                else{
                    file = files.get(0);
                    return file.getEntityName();
                }
            }
            return null;
        }
    }
}
